package cn.xing.modules.app.service.impl;

import cn.xing.config.SmsConfig;
import cn.xing.modules.app.service.SmsService;
import com.aliyun.oss.ClientException;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsConfig smsConfig;

    @Value("${alibaba.sms.open: false}")
    private boolean smsOpen;
    @Override
    public void sendSms(String phone, String code) {
        if(smsOpen){
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsConfig.getAccessKey(), smsConfig.getAccessSecret());
            IAcsClient client = new DefaultAcsClient(profile);

            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            // 手机号
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", "零星");
            request.putQueryParameter("TemplateCode", "SMS_204761190");
            // 验证码
            request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
            try {
                CommonResponse response = client.getCommonResponse(request);
                log.info(response.getData());

            } catch (ClientException | com.aliyuncs.exceptions.ClientException e) {
                log.warn("短信发送失败，原因：[{}]", e.getMessage());
                e.printStackTrace();
            }
        }


    }
}
